﻿using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug.VDDIC_Gamma_Demura
{
    public partial class NT38350_M : Form
    {
        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke 
        ListBox[] listbox = new ListBox[12];

        NumericUpDown[] Rvalue = new NumericUpDown[32];
        NumericUpDown[] Gvalue = new NumericUpDown[32];
        NumericUpDown[] Bvalue = new NumericUpDown[32];
        List<NumericUpDown> my = new List<NumericUpDown>();
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过

        private byte[] Rec_tmp = new byte[1];

        private static bool Gamma_adjust_timeout_flag = false;
        Color[] listBoxBackColor = new Color[3] { Color.Red, Color.Green, Color.Blue };
        string[] strRGB = new string[3] { "R", "G", "B" };

        int Total_points = 0;

        int error_flag = 0;   //0:ok,否则格式错误
        private int index = 0;
        private int flag1 = 1; //lum
        private int flag2 = 1; //x
        private int flag3 = 1; //y
        frmMain frmHelp = null;

        #region //多绑点需要更改的地方  regType=0
        #region //regType=0

        public ushort[] gamma_r_0_13 = new ushort[13]
        {
             0x0001,0x0203,0x0405,0x0607,0x0809,0x0A0B,0x1213,0x1C1D,0x2021,0x2425,0x2829,0x2D2F,0x3637
        };
        public ushort[] gamma_g_0_13 = new ushort[13]
        {
             0x3839,0x3A3B,0x3D3F,0x4041,0x4243,0x4445,0x4C4D,0x5758,0x5B5C,0x5F60,0x6364,0x6768,0x6F70
        };
        public ushort[] gamma_b_0_13 = new ushort[13]
        {
             0x7172,0x7374,0x7576,0x7778,0x797A,0x7B7C,0x8384,0x8D8E,0x9192,0x9596,0x999A,0x9D9E,0xA6A7
        };
        string[] gammaPage = { "fe,50", "fe,60", "fe,30", "fe,52" };
        string[] gammaPointSelect = { "ab,01", "ab,81" };   //27point or 13piont

        public ushort[] gamma_r_0_27 = new ushort[27]
        {
            0x0001,0x0203,0x0405,0x0607,0x0809,0x0A0B,0x0C0D,0x0E0F,0x1011,
            0x1213,0x1415,0x1617,0x1819,0x1A1B,0x1C1D,0x1E1F,0x2021,0x2223,
            0x2425,0x2627,0x2829,0x2A2B,0x2D2F,0x3031,0x3233,0x3435,0x3637
        };
        public ushort[] gamma_g_0_27 = new ushort[27]
        {
            0x3839,0x3A3B,0x3D3F,0x4041,0x4243,0x4445,0x4647,0x4849,0x4A4B,
            0x4C4D,0x4E4F,0x5052,0x5354,0x5556,0x5758,0x595A,0x5B5C,0x5D5E,
            0x5F60,0x6162,0x6364,0x6566,0x6768,0x696A,0x6B6C,0x6D6E,0x6F70
        };
        public ushort[] gamma_b_0_27 = new ushort[27]
        {
            0x7172,0x7374,0x7576,0x7778,0x797A,0x7B7C,0x7D7E,0x7F80,0x8182,
            0x8384,0x8586,0x8788,0x898A,0x8B8C,0x8D8E,0x8F90,0x9192,0x9394,
            0x9596,0x9798,0x999A,0x9B9C,0x9D9E,0x9FA0,0xA2A3,0xA4A5,0xA6A7
        };
        #endregion
        #region //regType=1
        string[] gammaPage_1 = { "ff,21" };
        string[] gammaPoint_1 = { "" };
        ushort[] gamma_Type1_gamma1_27 = new ushort[] { 0xB2, 0x10, 0xB3, 0x10, 0xB4, 0x10, 0xB5, 0x06, 0xB6, 0x10, 0xB7, 0x10, 0xB8, 0x10, 0xB9, 0x06, 0xBA, 0x10, 0xBB, 0x10, 0xBC, 0x10, 0xBD, 0x06 };//寄存器+回读个数
        ushort[] gamma_Type1_gamma2_27 = new ushort[] { 0xBF, 0x10, 0xC0, 0x10, 0xC1, 0x10, 0xC2, 0x06, 0xC3, 0x10, 0xC4, 0x10, 0xC5, 0x10, 0xC6, 0x06, 0xC7, 0x10, 0xC8, 0x10, 0xC9, 0x10, 0xCA, 0x06 };//寄存器+回读个数
        ushort[] gamma_Type1_gamma3_27 = new ushort[] { 0xCC, 0x10, 0xCD, 0x10, 0xCE, 0x10, 0xCF, 0x06, 0xD0, 0x10, 0xD1, 0x10, 0xD2, 0x10, 0xD3, 0x06, 0xD4, 0x10, 0xD5, 0x10, 0xD6, 0x10, 0xD7, 0x06 };//寄存器+回读个数
        ushort[] gamma_Type1_gamma4_27 = new ushort[] { 0xDA, 0x10, 0xDB, 0x10, 0xDC, 0x10, 0xDD, 0x06, 0xDE, 0x10, 0xDF, 0x10, 0xE0, 0x10, 0xE1, 0x06, 0xE2, 0x10, 0xE3, 0x10, 0xE4, 0x10, 0xE5, 0x06 };//寄存器+回读个数
        ushort[] gamma_Type1_gamma5_27 = new ushort[] { 0xE8, 0x10, 0xE9, 0x10, 0xEA, 0x10, 0xEB, 0x06, 0xEC, 0x10, 0xED, 0x10, 0xEE, 0x10, 0xEF, 0x06, 0xF0, 0x10, 0xF1, 0x10, 0xF2, 0x10, 0xF3, 0x06 };//寄存器+回读个数

        ushort[] gamma_Type1_gamma1_15 = new ushort[] { 0xB2, 0x10, 0xB3, 0x0E, 0xB6, 0x10, 0xB7, 0x0E, 0xBA, 0x10, 0xBB, 0x0E };//寄存器+回读个数
        ushort[] gamma_Type1_gamma2_15 = new ushort[] { 0xBF, 0x10, 0xC0, 0x0E, 0xC3, 0x10, 0xC4, 0x0E, 0xC7, 0x10, 0xC8, 0x0E };//寄存器+回读个数
        ushort[] gamma_Type1_gamma3_15 = new ushort[] { 0xCC, 0x10, 0xCD, 0x0E, 0xD0, 0x10, 0xD1, 0x0E, 0xD4, 0x10, 0xD5, 0x0E };//寄存器+回读个数
        ushort[] gamma_Type1_gamma4_15 = new ushort[] { 0xDA, 0x10, 0xDB, 0x0E, 0xDE, 0x10, 0xDF, 0x0E, 0xE2, 0x10, 0xE3, 0x0E };//寄存器+回读个数
        ushort[] gamma_Type1_gamma5_15 = new ushort[] { 0xE8, 0x10, 0xE9, 0x0E, 0xEC, 0x10, 0xED, 0x0E, 0xF0, 0x10, 0xF1, 0x0E };//寄存器+回读个数//寄存器+回读个数
                                                                                                                                 //    ushort[] gamma_b_1_27 = new ushort[] { 0xBA, 0x10, 0xBB, 0x10, 0xBC, 0x10, 0xBD, 0x06 };
        int[] regRmapping27 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };//读到的寄存器值高位在前，结合寄存器，低灰阶在前
        int[] regGmapping27 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
        int[] regBmapping27 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
        int[] regRmapping15 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 };//读到的寄存器值高位在前，结合寄存器，低灰阶在前
        int[] regGmapping15 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 };
        int[] regBmapping15 = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 };
        #endregion
        private void get_reg_address()
        {
            if (regType == 0)
            {
                if (rb_27_point.Checked == true)
                {
                    DDIC_Reg_write(gammaPage[(int)gamma_set.Value]);
                    DDIC_Reg_write(gammaPointSelect[0]);
                    gamma_r = gamma_r_0_27;
                    gamma_g = gamma_g_0_27;
                    gamma_b = gamma_b_0_27;
                }
                else if (rb_other_point.Checked == true)
                {
                    DDIC_Reg_write(gammaPage[(int)gamma_set.Value]);
                    DDIC_Reg_write(gammaPointSelect[1]);
                    gamma_r = gamma_r_0_13;
                    gamma_g = gamma_g_0_13;
                    gamma_b = gamma_b_0_13;
                }
                else   //非实际绑点default如下 防止越界
                {
                    gamma_r = new ushort[32];
                    gamma_g = new ushort[32];
                    gamma_b = new ushort[32];
                }
            }
            else if (regType == 1)
            {
                DDIC_Reg_write(gammaPage_1[0]);
                List<ushort[]> tmpGammaSet27 = new List<ushort[]> { gamma_Type1_gamma1_27, gamma_Type1_gamma2_27, gamma_Type1_gamma3_27, gamma_Type1_gamma4_27, gamma_Type1_gamma5_27 };
                List<ushort[]> tmpGammaSet15 = new List<ushort[]> { gamma_Type1_gamma1_15, gamma_Type1_gamma2_15, gamma_Type1_gamma3_15, gamma_Type1_gamma4_15, gamma_Type1_gamma5_15 };
                if (rb_27_point.Checked == true)
                {
                    gamma_r = tmpGammaSet27[(int)gamma_set.Value];
                    currentRmapping = regRmapping27;
                    currentGmapping = regGmapping27;
                    currentBmapping = regBmapping27;
                }
                else if (rb_other_point.Checked == true)
                {
                    gamma_r = tmpGammaSet15[(int)gamma_set.Value];
                    currentRmapping = regRmapping15;
                    currentGmapping = regGmapping15;
                    currentBmapping = regBmapping15;
                }
                else   //非实际绑点default如下 防止越界
                {
                    gamma_r = new ushort[32];
                    gamma_g = new ushort[32];
                    gamma_b = new ushort[32];
                }
            }
        }
        #region// 全局变量
        int regType = 1;       //0:寄存器一对一方式  1：寄存器一对多方式   zhongyao 
        ushort[] gamma_r = new ushort[] { };   //reg address
        ushort[] gamma_g = new ushort[] { };
        ushort[] gamma_b = new ushort[] { };
        ushort[] gamma_r_1 = new ushort[] { };
        ushort[] gamma_g_1 = new ushort[] { };
        ushort[] gamma_b_1 = new ushort[] { };
        int[] currentBmapping = new int[] { };
        int[] currentGmapping = new int[] { };
        int[] currentRmapping = new int[] { };
        int currentGammaSet = 0;
        #endregion

        #endregion //多绑点需要更改的地方
        //Gamma保存
        private void DDIC_Reg_write(string str)
        {
            string[] strt = str.Split(',');
            byte[] Send_buf = new byte[strt.Length + 5];
            Send_buf[0] = 0x7F;//NT38350_M
            Send_buf[1] = 0x01;//NT38350_M
            Send_buf[2] = (byte)strt.Length;
            for (int i = 0; i < strt.Length; i++)
            {
                Send_buf[3 + i] = byte.Parse((Convert.ToInt32(strt[i], 16)).ToString());
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[strt.Length + 5 - 2], out Send_buf[strt.Length + 5 - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, strt.Length + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void DDIC_Reg_read(string str)
        {
            string[] strt = str.Split(',');
            byte[] Send_buf = new byte[strt.Length + 5];
            Send_buf[0] = 0x7F;//NT38350_M
            Send_buf[1] = 0x02;//NT38350_M
            Send_buf[2] = (byte)strt.Length;
            for (int i = 0; i < strt.Length; i++)
            {
                Send_buf[3 + i] = byte.Parse((Convert.ToInt32(strt[i], 16)).ToString());
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[strt.Length + 5 - 2], out Send_buf[strt.Length + 5 - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, strt.Length + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void Gamma_read_all(int type)
        {
            if (type == 0)
            {
                byte[] Send_buf = new byte[Total_points * 6 + 5];
                System.Diagnostics.Debug.Print("sendbuf length =" + Send_buf.Length.ToString());
                Setting.TempRecord.cmdLen = Total_points * 6 + 5;

                Send_buf[0] = 0x7F;//NT38350_M
                Send_buf[1] = 0x06; //register normal gamma

                Send_buf[2] = Convert.ToByte(Total_points * 6); //length
                for (int i = 0; i < Total_points; i++)

                {
                    Send_buf[2 * i + 3] = Convert.ToByte(gamma_r[i] >> 8);   //高位
                    Send_buf[2 * i + 4] = Convert.ToByte(gamma_r[i] & 0xff);    //低位

                    Send_buf[Total_points * 2 + 2 * i + 3] = Convert.ToByte(gamma_g[i] >> 8);   //高位
                    Send_buf[Total_points * 2 + 2 * i + 4] = Convert.ToByte(gamma_g[i] & 0xff);    //低位

                    Send_buf[Total_points * 4 + 2 * i + 3] = Convert.ToByte(gamma_b[i] >> 8);   //高位
                    Send_buf[Total_points * 4 + 2 * i + 4] = Convert.ToByte(gamma_b[i] & 0xff);    //低位

                }
                string str = "";
                for (int i = 3; i < Total_points * 6 + 5; i++)
                {
                    str = str + String.Format("{0:X4}", Send_buf[i]) + ",";
                    if ((i - 3) % Total_points == 0)
                    {
                        str = str + "\r\n";
                    }
                }
                System.Diagnostics.Debug.Print(str);
                CRCData.CalculateCrc16(Send_buf, out Send_buf[Total_points * 6 + 5 - 2], out Send_buf[Total_points * 6 + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, Total_points * 6 + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
            else if (type == 1)
            {
                Setting.TempRecord.cmdLen = 0;
                byte[] Send_buf = new byte[gamma_r.Length + 5];
                System.Diagnostics.Debug.Print("sendbuf length =" + Send_buf.Length.ToString());
                for (int a = 0; a < gamma_r.Length / 2; a++)
                {
                    Setting.TempRecord.cmdLen = Setting.TempRecord.cmdLen + gamma_r[1 + 2 * a];
                }
                Setting.TempRecord.cmdLen = Setting.TempRecord.cmdLen + 5;
                Send_buf[0] = 0x7F;//NT38350_M
                Send_buf[1] = 0x07; //register normal gamma
                Send_buf[2] = (Byte)gamma_r.Length;
                for (int i = 0; i < gamma_r.Length; i++)
                {
                    Send_buf[3 + i] = (byte)gamma_r[i];
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[gamma_r.Length + 5 - 2], out Send_buf[gamma_r.Length + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, gamma_r.Length + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
        }
        private void Gamma_write_all(int type)
        {
            ushort r = 0, g = 0, b = 0;
            if (type == 0)
            {
                for (int i = 0; i < Total_points; i++)

                {
                    r = (ushort)Rvalue[i].Value;
                    g = (ushort)Gvalue[i].Value;
                    b = (ushort)Bvalue[i].Value;
                    Auto_gamma_write(gamma_r[i], r, gamma_g[i], g, gamma_b[i], b);
                }
            }
            else if (type == 1)
            {

                int dateLeghth = 0;
                for (int i = 0; i < gamma_r.Length / 2; i++)
                {
                    dateLeghth = dateLeghth + gamma_r[1 + 2 * i] + 2;
                }
                System.Diagnostics.Debug.Print(dateLeghth.ToString());
                byte[] Send_buf = new byte[dateLeghth + 5];

                Send_buf[0] = 0x7F;//NT38350_M
                Send_buf[1] = 0x05; //register normal gamma
                Send_buf[2] = (byte)(dateLeghth);

                byte[] tempR = new byte[currentRmapping.Length];
                byte[] tempG = new byte[currentRmapping.Length];
                byte[] tempB = new byte[currentRmapping.Length];
                byte[] temp_all = new byte[currentRmapping.Length * 3];
                //数据和寄存器值开始拼接+映射
                {
                    for (int i = 0; i < Total_points; i++)
                    {
                        tempR[currentRmapping[2 * i]] = Convert.ToByte((int)Rvalue[i].Value >> 8);
                        tempR[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Rvalue[i].Value & 0xff);
                        tempG[currentRmapping[2 * i]] = Convert.ToByte((int)Gvalue[i].Value >> 8);
                        tempG[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Gvalue[i].Value & 0xff);
                        tempB[currentRmapping[2 * i]] = Convert.ToByte((int)Bvalue[i].Value >> 8);
                        tempB[currentRmapping[2 * i + 1]] = Convert.ToByte((int)Bvalue[i].Value & 0xff);
                    }
                    tempR.CopyTo(temp_all, 0);
                    tempG.CopyTo(temp_all, currentRmapping.Length);
                    tempB.CopyTo(temp_all, currentRmapping.Length * 2);
                    List<byte> allList = new List<byte>(temp_all);
                    int position1 = 0;
                    for (int i = 0; i < gamma_r.Length / 2; i++)
                    {
                        allList.Insert(0 + position1, (byte)(gamma_r[2 * i + 1] + 1));
                        allList.Insert(1 + position1, (byte)(gamma_r[2 * i]));
                        position1 = position1 + gamma_r[2 * i + 1] + 2;
                    }
                    for (int j = 0; j < currentRmapping.Length * 3 + gamma_r.Length; j++)
                    {
                        Send_buf[3 + j] = allList[j];
                    }
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[dateLeghth + 5 - 2], out Send_buf[dateLeghth + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, dateLeghth + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }

        }
        public NT38350_M()
        {
            //InitializeComponent();
            //btnCalculate_Click(null,null);
            //AddlistBox();
            //AddValueText();
        }
        public NT38350_M(frmMain myfast)
        {
            frmHelp = myfast;
            InitializeComponent();
            AddlistBox();
            AddValueText();
            frmHelp.Child_window_hide_already = true;
            frmHelp.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体   
        }
        private void NT38350_M_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(NT38350_M_DataReceived);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            frmHelp.Child_window_hide_already = false;
            frmHelp.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormClosed！\r\n";
            frmHelp.IC_comboBox.Enabled = true;
            save_current_cfg(null, null);
        }
        private void NT38350_M_VisibleChanged(object sender, EventArgs e)
        {
            if (frmHelp.Child_window_hide_already == false) //子窗体已开启标识
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(NT38350_M_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormHide！\r\n";
                frmHelp.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(NT38350_M_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormOpened！\r\n";
                frmHelp.Child_window_hide_already = false; //子窗体已开启标识  
            }
        }

        private void NT38350_M_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (IClosing)
                return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmHelp.comPort.BytesToRead;
                byte[] buf = new byte[n];
                byte data;

                frmHelp.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到   
                buffer.Clear();
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    // 0x7E: NT38350 的Gamma读写、寄存器读写、OTP读写    设置  返回
                    if (buffer[0] == 0x7F && Setting.TempRecord.cmdLen > 0)
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    else
                    {
                        buffer.RemoveRange(0, buffer.Count);
                    }
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmHelp.T1.Enabled = false; //停止超时计数
                        if (Rec_tmp[0] == 0x7F) //NT38350
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA Update\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x07:    //regType=0
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA Update\t读 OK！\r\n";
                                        for (int i = 0; i < Total_points; i++)
                                        {

                                            Rvalue[i].Value = (Rec_tmp[3 + currentRmapping[2 * i]]) << 8 | (Rec_tmp[3 + currentRmapping[2 * i + 1]]);
                                            //  Rvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + currentRmapping[2*i]] )* 256+Convert.ToInt16(Rec_tmp[3 + currentRmapping[2 * i + 1]]);
                                            Gvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + Total_points * 2 + currentGmapping[2 * i]]) * 256 + Convert.ToInt16(Rec_tmp[3 + Total_points * 2 + currentGmapping[2 * i + 1]]);
                                            Bvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + Total_points * 4 + currentBmapping[2 * i]]) * 256 + Convert.ToInt16(Rec_tmp[3 + Total_points * 4 + currentBmapping[2 * i + 1]]);
                                        }
                                    }
                                    break;
                                case 0x03:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "delay OK！\r\n";
                                    }
                                    break;
                                case 0x04:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA Update\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x08:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x06:     //regType=0
                                    {
                                        for (int i = 0; i < Total_points; i++)
                                        {
                                            Rvalue[i].Value = 10 * i;
                                            //  System.Diagnostics.Debug.Print(Convert.ToInt16(Rec_tmp[3 + 2 * i]).ToString());
                                            Rvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + 2 * i]) * 256 + Convert.ToInt16(Rec_tmp[4 + 2 * i]);
                                            Gvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + 2 * i + Total_points * 2]) * 256 + Convert.ToInt16(Rec_tmp[4 + 2 * i + Total_points * 2]);
                                            Bvalue[i].Value = Convert.ToInt16(Rec_tmp[3 + 2 * i + Total_points * 4]) * 256 + Convert.ToInt16(Rec_tmp[4 + 2 * i + Total_points * 4]);
                                        }
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t 读OK！\r\n";

                                    }
                                    break;
                                case 0x0D:
                                    {

                                    }
                                    break;
                                default: break;
                            }
                        }
                        frmHelp.textBox1.SelectionStart = this.frmHelp.textBox1.Text.Length;
                        frmHelp.textBox1.ScrollToCaret();//滚动到光标处
                        if (frmHelp.textBox1.Lines.Length > 250) frmHelp.textBox1.Text = null;
                    }));
                }

            }
            finally
            {
                Listening = false;
            }
        }




        #region  //界面设置
        private void AddlistBox()
        {
            for (int a = 0; a < 3; a++)
            {
                for (int i = 0; i < 4; i++)
                {
                    listbox[i + a * 4] = new System.Windows.Forms.ListBox();
                    listbox[i + a * 4].FormattingEnabled = true;
                    listbox[i + a * 4].ItemHeight = 12;
                    listbox[i + a * 4].Location = new System.Drawing.Point(0 + 95 * i, 15 + a * 170);
                    // listbox[i].Name = listName[i+4*a];
                    listbox[i + a * 4].Size = new System.Drawing.Size(50, 168);
                    listbox[i + a * 4].TabIndex = i;
                    listbox[i + a * 4].Font = new System.Drawing.Font("宋体", 15F); ;
                    listbox[i + a * 4].BackColor = listBoxBackColor[a];
                    listbox[i + a * 4].ForeColor = Color.Black;
                    for (int j = 0; j < 8; j++)
                    {
                        listbox[i + a * 4].Items.Add(strRGB[a] + "XXX");
                    }
                    groupBox1.Controls.Add(listbox[i + a * 4]);
                }
            }
        }
        private void AddValueText()
        {
            List<NumericUpDown[]> numUpDown = new List<NumericUpDown[]> { Rvalue, Gvalue, Bvalue };
            for (int a = 0; a < 3; a++)
            {
                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        numUpDown[a][j + i * 8] = new System.Windows.Forms.NumericUpDown();
                        numUpDown[a][j + i * 8].Location = new System.Drawing.Point(50 + 95 * i, 15 + j * 21 + a * 170);
                        numUpDown[a][j + i * 8].Size = new System.Drawing.Size(40, 10);
                        numUpDown[a][j + i * 8].Maximum = 0xfff;
                        numUpDown[a][j + i * 8].Hexadecimal = true;
                        groupBox1.Controls.Add(numUpDown[a][j + i * 8]);
                    }
                }
            }
        }
        #endregion


        private void btnCalculate_Click(object sender, EventArgs e)
        {
            {
                double Lr_d, Lg_d, Lb_d;
                int specFlag = 0;
                string[] arr = txtSpec.Lines;

                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);

                            if (specFlag == 1)   //multi 时避免多次计算
                                break;
                            specFlag++;
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                        else if (line.Contains("__GAMMA_SET"))

                        {
                            gamma_set.Text = line.Substring(line.IndexOf("(") + 1, 1);
                        }
                    }

                    std_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                    std_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                    std_yoff.Text = Diven_Offset[0].Y_OFF.ToString();

                    Total_points = Diven_Gamma[0].Points_num;
                    if (Total_points == 27)
                        rb_27_point.Checked = Enabled;
                    else
                        rb_other_point.Checked = Enabled;
                    D_lums = new double[Total_points, 3];
                    D_lum = new double[Total_points];

                    std_gamma.Text = Diven_Gamma[0].Curve.ToString();
                    std_lum.Text = Diven_Gamma[0].Lum.ToString();
                    std_x.Text = Diven_Gamma[0].X.ToString();
                    std_y.Text = Diven_Gamma[0].Y.ToString();
                    for (int p = 0; p < Total_points; p++)
                    {   //Diven_Offset[p].NO 灰阶绑点                 
                        D_lum[p] = (Math.Pow((Diven_Offset[p].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                    }
                    CaSDKObj.YUV_to_RGB(Diven_Gamma[0].Y, Diven_Gamma[0].X, out Lr_d, out Lb_d, out Lg_d);//R/B/G分亮度转换
                    for (int i = 0; i < Total_points; i++)
                    {
                        D_lums[i, 0] = D_lum[i] * Lr_d; //R/B/G分亮度计算
                        D_lums[i, 1] = D_lum[i] * Lg_d;
                        D_lums[i, 2] = D_lum[i] * Lb_d;
                    }
                }
                catch
                {
                    File.Delete(@"c:\Users\Public\2KMainForm\GammaConfig");
                    error_flag++;
                    MessageBox.Show("格式输入有误!!");
                    return;
                }

            }
        }


        private void show_RGB_value(object sender, EventArgs e)
        {
            for (int i = 0; i < 32 - Total_points; i++)    //用不到的地方直接黑
            {
                if (Rvalue[31 - i].Enabled == true)
                {
                    Rvalue[31 - i].Enabled = false;
                    Rvalue[31 - i].BackColor = Color.Gray;
                    Gvalue[31 - i].Enabled = false;
                    Gvalue[31 - i].BackColor = Color.Gray;
                    Bvalue[31 - i].Enabled = false;
                    Bvalue[31 - i].BackColor = Color.Gray;
                }
            }
            for (int i = 0; i < Total_points; i++)     //交叉部分
            {
                if (Rvalue[i].Enabled == false)
                {
                    Rvalue[i].Enabled = true;
                    Gvalue[i].Enabled = true;
                    Bvalue[i].Enabled = true;
                    Rvalue[i].BackColor = Color.White;
                    Gvalue[i].BackColor = Color.White;
                    Bvalue[i].BackColor = Color.White;
                }
            }
            try
            {
                for (int a = 0; a < 3; a++)  //填充灰阶
                {
                    for (int i = 0; i < 4; i++)
                    {
                        listbox[i + a * 4].Items.Clear();

                        for (int j = 0; j < 8; j++)
                        {
                            if ((j + 8 * i) >= Diven_Gamma[0].Points_num)
                            { break; }
                            listbox[i + a * 4].Items.Add(strRGB[a] + Diven_Offset[Diven_Gamma[0].Points_num - 1 - (i * 8 + j)].NO.ToString());
                        }

                    }
                }
            }
            catch
            {

                for (int j = 0; j < 8; j++)
                {
                    listbox[0].Items.Add(strRGB[0] + "XXX");
                    error_flag++;
                }
                MessageBox.Show("关闭即将跳出的窗口，重新进入.....");
                return;

            }
        }
        private void open_txt_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "精度配置文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "gamma cfg write";

            if (of.ShowDialog() == DialogResult.OK)
            {
                txtSpec.Clear();
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                while (str_generate != null)
                {
                    txtSpec.AppendText(str_generate + "\r\n");
                    str_generate = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                btnCalculate_Click(null, null);
                get_reg_address();
                show_RGB_value(null, null);
            }
        }

        private void save_txt_Click(object sender, EventArgs e)
        {
            if (txtSpec.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else
            {
                //创建保存对话框对象
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "gamma cfg files (*.txt)|*.txt"; //过滤文件类型
                save.FilterIndex = 1;
                save.RestoreDirectory = true;
                if (save.ShowDialog() == DialogResult.OK)
                {
                    string path = save.FileName;
                    save.DefaultExt = ".txt";
                    StreamWriter sw = new StreamWriter(path);
                    sw.WriteLine(txtSpec.Text);
                    sw.Close();
                }
            }
        }
        private void open_gamma_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            string strtmp = "";
            of.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*";
            of.Title = "打开Gamma文件";
            if (of.ShowDialog() == DialogResult.OK)
            //读取文本信息
            {
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                //循环读取文本信息
                while (!string.IsNullOrEmpty(strLine))
                {
                    strtmp = strtmp + strLine + ",";
                    strLine = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                for (int i = 0; i < Total_points; i++)
                {
                    Rvalue[i].Text = arrtmp[1 + 6 * i].ToString();
                    Gvalue[i].Text = arrtmp[3 + 6 * i].ToString();
                    Bvalue[i].Text = arrtmp[5 + 6 * i].ToString();
                }
            }
        }
        private void save_gamma_Click(object sender, EventArgs e)
        {

            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "保存Gamma文件";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                    for (int i = 0; i < Total_points; i++)
                    {

                        str = str + "R" + Diven_Offset[i].NO.ToString() + "," + Rvalue[i].Text + ","
                          + "G" + Diven_Offset[i].NO.ToString() + "," + Gvalue[i].Text + ","
                          + "B" + Diven_Offset[i].NO.ToString() + "," + Bvalue[i].Text + "\r\n";
                    }
                    sw.WriteLine(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Gamma保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Gamma保存时发生错误，请再试！", "系统提示：");
                }
            }
        } //
        private void btnReadWriteGamma_Clicked(object sender, EventArgs e)
        {

            ushort r = 0, g = 0, b = 0;
            Button btnTemp = (Button)sender;
            get_reg_address();
            switch (btnTemp.Name)
            {
                case "btn_Gwrite":
                    {
                        Gamma_write_all(regType);
                    }
                    break;
                case "btn_RGBread":
                    {
                        Gamma_read_all(regType);
                    }
                    break;
                default:
                    break;
            }
        }

        private void btnAutoGammas_Click(object sender, EventArgs e)
        {
            index = 0;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;

            //if (NT37350_AOD_Inter_cbx.Checked == true)  //AOD gamma adjust in AOD mode or not
            //{
            //    Load_GammmPic(Diven_Offset[index].NO.ToString()); //Load pic
            //}
            //else
            //
            frmHelp.numPatternR.Value = Diven_Offset[index].NO;
            frmHelp.numPatternG.Value = Diven_Offset[index].NO;
            frmHelp.numPatternB.Value = Diven_Offset[index].NO;
            Application.DoEvents();
            frmHelp.OLED_Show_Click(frmHelp.btnwhite, e);

            Thread.Sleep(10);
            T20.Interval = 300;
            T20.Enabled = true;

        }

        private void T20_Tick(object sender, EventArgs e)
        {
            Adjust_gamma(null, null);
        }
        private void Adjust_gamma(Object myObject, EventArgs e)
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            frmHelp.Msr_CASDK();
            if (Gamma_adjust_timeout_flag == true)//如果是0绑点
            {
                flag1 = 0;
                flag2 = 0;
                flag3 = 0;
            }
            else
            {
                if ((frmHelp.CASDK_LUM < (D_lum[index] + D_lum[index] * Diven_Offset[index].LUM_OFF / 100)) && (frmHelp.CASDK_LUM > (D_lum[index] - D_lum[index] * Diven_Offset[index].LUM_OFF / 100)))//G
                { flag1 = 0; }
                else
                { flag1 = 1; }
                if ((frmHelp.CASDK_x < (Diven_Gamma[0].X + Diven_Offset[index].X_OFF)) && (frmHelp.CASDK_x > (Diven_Gamma[0].X - Diven_Offset[index].X_OFF)) && flag1 == 0)//R
                { flag3 = 0; }
                else
                { flag3 = 1; }
                if ((frmHelp.CASDK_y < (Diven_Gamma[0].Y + Diven_Offset[index].Y_OFF)) && (frmHelp.CASDK_y > (Diven_Gamma[0].Y - Diven_Offset[index].Y_OFF)) && flag1 == 0 && flag3 == 0)//B
                { flag2 = 0; }
                else
                { flag2 = 1; }

            }
            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T20.Enabled = false;
                //reset-----
                Gamma_adjust_timeout_flag = false;
                frmHelp.Gamma_auto_adjust_count = 0;
                //--------
                index++;

                if (index == Total_points - 1)
                {
                    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "gamma调试完毕!\r\n";
                    //---------------------------------add-------------------------------------
                    if (Multi_gamma_txt_next_index < Multi_gamma_txt_line_count)
                    {
                        Multi_gamma_txt_now_index = Multi_gamma_txt_next_index;
                        Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
                    }
                    //---------------------------------add-------------------------------------
                }
                if (index < Total_points - 1)
                {
                    //if (NT37350_AOD_Inter_cbx.Checked == true)  //AOD gamma adjust in AOD mode or not
                    //{
                    //    Load_GammmPic(Diven_Offset[index].NO.ToString()); //Load pic
                    //}
                    //else
                    //{
                    frmHelp.numPatternR.Value = Diven_Offset[index].NO;//固定255灰阶
                    frmHelp.numPatternG.Value = Diven_Offset[index].NO;
                    frmHelp.numPatternB.Value = Diven_Offset[index].NO;
                    Application.DoEvents();
                    frmHelp.OLED_Show_Click(frmHelp.btnPatternW, null);//写入Pattern参数

                    Thread.Sleep(500); //1秒=1000毫秒，
                    T20.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
            }
            else  //进入调试步骤
            {
                decimal r = 0, g = 0, b = 0;
                CaSDKObj.YUV_to_RGB(frmHelp.CASDK_y, frmHelp.CASDK_x, out Lr_t, out Lb_t, out Lg_t);
                lumr = frmHelp.CASDK_LUM * Lr_t;
                lumg = frmHelp.CASDK_LUM * Lg_t;
                lumb = frmHelp.CASDK_LUM * Lb_t;

                try
                {
                    frmHelp.Gamma_auto_adjust_count_set = 50;
                    if (index == Total_points - 1)
                    {
                        Rvalue[Total_points - 1 - index].Value = 0;
                        Gvalue[Total_points - 1 - index].Value = 0;
                        Bvalue[Total_points - 1 - index].Value = 0;
                        r = 0;
                        g = 0;
                        b = 0;
                        // frmHelp.auto_gamma_write(gamma_r[Diven_Gamma[0].Points_num - 1 - index], 0, gamma_g[Diven_Gamma[0].Points_num - 1 - index], 0, gamma_b[Diven_Gamma[0].Points_num - 1 - index], 0);
                        Gamma_adjust_timeout_flag = true;
                    }
                    else
                    {
                        frmHelp.Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], Rvalue[Total_points - index - 1].Value, Gvalue[Total_points - index - 1].Value, Bvalue[Total_points - index - 1].Value, Diven_Offset[index].NO, 0x3ff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                        Rvalue[Total_points - index - 1].Value = r;
                        Gvalue[Total_points - index - 1].Value = g;
                        Bvalue[Total_points - index - 1].Value = b;

                        if (Gvalue[Total_points - index - 1].Value <= Gvalue[Total_points - index - 2].Value)
                        {
                            Rvalue[Total_points - index - 2].Value = r - 0x10;
                            Gvalue[Total_points - index - 2].Value = g - 0x10;
                            Bvalue[Total_points - index - 2].Value = b - 0x10;
                        }
                    }
                    if (regType == 0)
                    {
                        Auto_gamma_write(gamma_r[Total_points - 1 - index], (ushort)r, gamma_g[Total_points - 1 - index], (ushort)g, gamma_b[Total_points - 1 - index], (ushort)b);
                    }
                    else if (regType == 1)
                    {

                        btnReadWriteGamma_Clicked(btn_Gwrite, null);
                        Thread.Sleep(60);

                    }
                }
                catch
                {
                    T20.Enabled = false;
                    MessageBox.Show("调整数值超限");
                }
            }
        }
        private void Auto_gamma_write(UInt16 addr, UInt16 datar, UInt16 addg, UInt16 datag, UInt16 addb, UInt16 Datab)//一组gamma写入
        {
            byte[] Send_buf = new byte[18];
            Setting.TempRecord.cmdLen = 17;

            Send_buf[0] = 0x7F;//NT38350_M

            {
                Send_buf[1] = 0x04; //register normal gamma
            }          //{
                       //    Send_buf[1] = 0xDD; //register 
                       //}
            Send_buf[2] = 13; //length

            Send_buf[3] = Convert.ToByte(addr >> 8);
            Send_buf[4] = Convert.ToByte(datar >> 8);
            Send_buf[5] = Convert.ToByte(addr & 0xff);
            Send_buf[6] = Convert.ToByte(datar & 0xff);
            Send_buf[7] = Convert.ToByte(addg >> 8);
            Send_buf[8] = Convert.ToByte(datag >> 8);
            Send_buf[9] = Convert.ToByte(addg & 0xff);
            Send_buf[10] = Convert.ToByte(datag & 0xff);
            Send_buf[11] = Convert.ToByte(addb >> 8);
            Send_buf[12] = Convert.ToByte(Datab >> 8);
            Send_buf[13] = Convert.ToByte(addb & 0xff);
            Send_buf[14] = Convert.ToByte(Datab & 0xff);
            {
                Send_buf[15] = Convert.ToByte(0);
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[16], out Send_buf[17]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 18);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            T20.Enabled = false;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
        }
        private int Multi_gamma_txt_now_index = 0;
        private int Multi_gamma_txt_next_index;
        private int Multi_gamma_txt_line_count = 0;
        private int Multi_gamma_group_index = 0;
        private void btn_flexible_gamma_Click(object sender, EventArgs e)
        {
            Multi_gamma_txt_now_index = 0;
            Multi_gamma_txt_line_count = this.txtSpec.Lines.GetUpperBound(0);
            Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
        }
        private void Multi_flexible_gammas(int txt_index, out int list_view_index)
        {
            string strLine = Convert.ToString(txtSpec.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组
            string perline = string.Empty;
            string perline0 = string.Empty;
            list_view_index = 0;
            if (txtSpec.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else  //标记关键事件
            {
                try
                {
                    arr = strLine.Split('\n'); //以逗号分割，添加到数
                    for (int i = txt_index; i < arr.Length;)  //获取的行数
                    {
                        perline = arr[i];
                        perline = perline.Replace(" ", "");
                        perline = perline.Replace(".", "");
                        perline = perline.Replace(";", "");
                        perline = perline.Replace("(", "");
                        perline = perline.Replace(")", "");
                        perline = perline.Replace("\r", "");

                        if (perline.Contains("REGW"))
                        {
                            perline = perline.Replace("REGW", "");
                            frmHelp.Gen_BC_lab.Text = perline;
                            frmHelp.Generate_File_Click(frmHelp.Gen_DBC_control, null);
                            Thread.Sleep(100);
                            i = i + 1;
                        }
                        else if (perline.Contains("SAVE"))
                        {
                            string pathsave_file = System.Environment.CurrentDirectory + "\\l_gamma";
                            if (Directory.Exists(pathsave_file) == false)
                            {
                                Directory.CreateDirectory(pathsave_file);
                            }
                            string pathsave = System.Environment.CurrentDirectory + "\\l_gamma" + "\\gamma" + Multi_gamma_group_index.ToString() + ".csv";
                            Multi_SaveGamma(pathsave);
                            Thread.Sleep(50);
                            i = i + 1;
                        }
                        else if (perline.Contains("GAMMA_SET"))
                        {
                            perline = perline.Replace("GAMMA_SET", "");
                            perline = perline.Replace("_", "");
                            Multi_gamma_group_index = Convert.ToInt32(perline);
                            currentGammaSet = Multi_gamma_group_index;
                            gamma_set.Value = currentGammaSet;
                            get_reg_address();                     //jiao 重要
                            System.Collections.ArrayList list = new System.Collections.ArrayList();
                            do
                            {
                                i = i + 1;
                                perline = arr[i];
                                list.Add(perline + "\n");
                            } while (perline.Contains("GAMMA_TUNING") == false);
                            string[] gamma_set_lines = (string[])list.ToArray(typeof(string));
                            Text_Processing(gamma_set_lines);
                            try
                            {
                                string pathsave_file = System.Environment.CurrentDirectory + "\\l_gamma";
                                if (Directory.Exists(pathsave_file) == false)
                                {
                                    Directory.CreateDirectory(pathsave_file);
                                }
                                string pathload = System.Environment.CurrentDirectory + "\\l_gamma" + "\\gamma" + Multi_gamma_group_index.ToString() + ".csv";
                                Multi_LoadGamma(pathload);
                                Application.DoEvents();
                                btnReadWriteGamma_Clicked(btn_Gwrite, null);
                                Thread.Sleep(15);

                            }
                            catch {; }
                            btnAutoGammas_Click(null, null); //替换成相应IC的自动gamma启动函数名
                            list_view_index = i;
                            break;
                        }
                        else
                        {
                            i = i + 1;
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("输入格式有误！");
                }
            }
        }
        private void Multi_LoadGamma(string path)
        {
            string strtmp = "";
            //读取文本信息
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            string strLine = streamReader.ReadLine();
            //循环读取文本信息
            while (!string.IsNullOrEmpty(strLine))
            {
                strtmp = strtmp + strLine + ",";
                strLine = streamReader.ReadLine(); //循环读取下一行
            }
            fs.Close(); //关闭流
            streamReader.Close();
            string[] arrtmp = strtmp.Split(new Char[] { ',' });
            for (int i = 0; i < Total_points; i++)
            {
                Rvalue[i].Text = arrtmp[1 + 6 * i].ToString();
                Gvalue[i].Text = arrtmp[3 + 6 * i].ToString();
                Bvalue[i].Text = arrtmp[5 + 6 * i].ToString(); ;

            }
        }

        private void Text_Processing(string[] txt_path)
        {
            double Lr_d, Lg_d, Lb_d;
            string[] arr = txt_path;
            {
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
            }
            try  //获取调整spec
            {
                std_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                std_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                std_yoff.Text = Diven_Offset[0].Y_OFF.ToString();


                D_lums = new double[Total_points, 3];
                D_lum = new double[Total_points];

                std_gamma.Text = Diven_Gamma[0].Curve.ToString();
                std_lum.Text = Diven_Gamma[0].Lum.ToString();
                std_x.Text = Diven_Gamma[0].X.ToString();
                std_y.Text = Diven_Gamma[0].Y.ToString();

                for (int p = 0; p < Total_points; p++)
                {   //Diven_Offset[p].NO 灰阶绑点                 
                    D_lum[p] = (Math.Pow((Diven_Offset[p].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                }

                CaSDKObj.YUV_to_RGB(Diven_Gamma[0].Y, Diven_Gamma[0].X, out Lr_d, out Lb_d, out Lg_d);//R/B/G分亮度转换

                for (int i = 0; i < Total_points; i++)
                {
                    D_lums[i, 0] = D_lum[i] * Lr_d; //R/B/G分亮度计算
                    D_lums[i, 1] = D_lum[i] * Lg_d;
                    D_lums[i, 2] = D_lum[i] * Lb_d;
                }
            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
        }

        private void Multi_SaveGamma(string path)
        {
            string str = "保存Gamma文件";
            StreamWriter sw = null; //文件流
            sw = new StreamWriter(path, false, Encoding.UTF8);
            for (int i = 0; i < Total_points; i++)
            {

                str = str + "R" + Diven_Offset[i].NO.ToString() + "," + Rvalue[i].Text + ","
                  + "G" + Diven_Offset[i].NO.ToString() + "," + Gvalue[i].Text + ","
                  + "B" + Diven_Offset[i].NO.ToString() + "," + Bvalue[i].Text + "\r\n";
            }
            sw.WriteLine(str);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        } //

        private void NT38350_M_Load(object sender, EventArgs e)
        {
            string Config_path = @"c:\Users\Public\2KMainForm\GammaConfig";
            //  FileInfo cfg = new FileInfo(Config_path);

            if (!File.Exists(Config_path))
            {
                //  MessageBox.Show("cfg is not exist");
            }
            else
            {
                StreamReader sr = new StreamReader(Config_path, Encoding.UTF8);
                string tmp = "";

                for (; ; )
                {
                    tmp = sr.ReadLine();
                    if (tmp == null)
                        break;
                    //if(tmp.Contains("regType"))
                    //{
                    //    regType = Convert.ToInt16( tmp.Substring(tmp.IndexOf("=")+1,1));
                    //    System.Diagnostics.Debug.Print("reg:"+regType.ToString());
                    //}
                    //else if(tmp.Contains("Total_points"))
                    //{
                    //    Total_points = Convert.ToInt16(tmp.Substring(tmp.IndexOf("=")+1, 2));
                    //    total_point_show.Text = Total_points.ToString();
                    //}
                    if (tmp.Contains("gamma_set"))
                    {
                        txtSpec.Clear();
                        for (; ; )
                        {
                            tmp = sr.ReadLine();
                            if (tmp.Contains("gamma_set"))
                            {
                                break;
                            }
                            else
                            {
                                txtSpec.AppendText(tmp + "\r\n");
                            }
                        }
                    }
                    else if (tmp.Contains("gamma_r"))
                    {
                        string[] gamma_regR = sr.ReadLine().Split(',');
                        System.Diagnostics.Debug.Print("leght=" + gamma_regR.Length.ToString());
                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_r[i] = Convert.ToUInt16(gamma_regR[i], 16);
                            System.Diagnostics.Debug.Print(String.Format("{0:X4}", gamma_r[i]));
                        }
                    }
                    else if (tmp.Contains("gamma_r"))
                    {
                        string[] gamma_regR = sr.ReadLine().Split(',');
                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_r[i] = Convert.ToUInt16(gamma_regR[i], 16);
                            System.Diagnostics.Debug.Print(String.Format("{0:X4}", gamma_r[i]));
                        }
                    }
                    else if (tmp.Contains("gamma_g"))
                    {
                        string[] gamma_regG = sr.ReadLine().Split(',');
                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_g[i] = Convert.ToUInt16(gamma_regG[i], 16);
                        }
                    }
                    else if (tmp.Contains("gamma_b"))
                    {
                        string[] gamma_regB = sr.ReadLine().Split(',');

                        for (int i = 0; i < Total_points; i++)
                        {
                            gamma_b[i] = Convert.ToUInt16(gamma_regB[i], 16);

                        }
                    }
                    else if (tmp.Contains("end"))
                    {
                        System.Diagnostics.Debug.Print("readfinished!");
                        sr.Close();

                        break;
                    }
                    System.Diagnostics.Debug.Print(tmp);
                }
            }
            btnCalculate_Click(null, null);
            get_reg_address();
            show_RGB_value(null, null);
        }

        private void save_current_cfg(object sender, FormClosedEventArgs e)
        {
            if (error_flag != 0)
            {
                return;
            }
            string Config_path = @"c:\Users\Public\2KMainForm\GammaConfig";

            StreamWriter sw = new StreamWriter(Config_path, false, Encoding.UTF8);
            sw.WriteLine("regType=" + regType.ToString());
            sw.WriteLine("Total_points=" + Total_points.ToString());
            sw.WriteLine("[gamma_set]");
            sw.WriteLine(txtSpec.Text);
            string tempR = "";
            string tempG = "";
            string tempB = "";
            if (regType == 0)
            {
                for (int i = 0; i < Total_points; i++)
                {
                    if (i == Total_points - 1)
                    {
                        tempR = tempR + String.Format("{0:X4}", gamma_r[i]);
                        tempG = tempG + String.Format("{0:X4}", gamma_g[i]);
                        tempB = tempB + String.Format("{0:X4}", gamma_b[i]);
                    }
                    else
                    {
                        tempR = tempR + String.Format("{0:X4}", gamma_r[i]) + ",";
                        tempG = tempG + String.Format("{0:X4}", gamma_g[i]) + ",";
                        tempB = tempB + String.Format("{0:X4}", gamma_b[i]) + ",";
                    }
                }
            }

            sw.WriteLine("[gamma_set]");
            sw.WriteLine("[gamma_r]");
            sw.WriteLine(tempR);
            sw.WriteLine("[gamma_g]");
            sw.WriteLine(tempG);
            sw.WriteLine("[gamma_b]");
            sw.WriteLine(tempB);
            sw.WriteLine("[end]");
            sw.Close();
        }
    }
}
